from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import Question,QuestionType,Choice,Answer
from random import sample
from .oo import ProducePaper
from .produce import CreatePaper
from .cpaper import Cpaper
from .patch import PatchPaper
from login.models import SavePaper,PersonID,PersonSf,DefaultPaper,Batch
from django.utils import timezone
from django.urls import reverse
from django.db.models import Count
import time
from .batch_detail import BatchDetail
# Create your views here.
 
def student_index(request):
    try:
        permission = request.session['权限']
        student_name = request.session['student_name']
        print(student_name)
        #return render(request,'paper/student_index.html',context)
    except KeyError:
        context = {}
        return render(request,'login/denglu.html',context)
    else:
        request.session['权限'] = permission
        request.session['student_name'] = student_name
        name_id = PersonID.objects.get(person_name = student_name).id
        context = {'student_name':student_name,'id':name_id,'zhuce':'注册'}
        return render(request,'paper/student_index.html',context)

def student_detail(request):
    try:
        permission = request.session['权限']
        student_name = request.session['student_name']
    except KeyError:
        context = {'message':'请先登录！'}
        return render(request,'login/denglu.html',context)
    else:  
        paper_obj_list = PersonID.objects.get(person_name = student_name).savepaper_set.all()
        print(paper_obj_list)
        if len(list(paper_obj_list)) == 0:
            context = {'error':'你还没有考过试，请先考试！','student_name':student_name}
            return render(request,'paper/student_index.html',context)
        else:
            last_info_dict = {}
            for paper_obj in paper_obj_list:
                last_info_dict[paper_obj] = BatchDetail(paper_obj).BatchConvert()
                
            #the_paper_obj = paper_obj_list[0]
            #last_info_dict = BatchDetail(the_paper_obj).BatchConvert()
            #print(last_info_dict)
            context = {'last_info_dict':last_info_dict,'student_name':student_name}
            return render(request,'paper/student_detail.html',context)
    
def teacher_index(request):#老师选择试卷或者生成新的试卷
    try:
        permission = request.session['权限']         
    except KeyError:
        context = {}
        return render(request,'login/denglu.html',context)
    else:
        teacher_name = request.session['teacher_name']
    '''
        if permission == '老师':
            username = request.session['username']
        else:
            context = {}
            return render(request,'login/denglu.html',context)
    '''      
    
    qu_type_list = QuestionType.objects.all()
    #所有问题类型的QuerySet
    type_list = []
    type_dict = {}
    qu_type_list2 = [qu_type for qu_type in qu_type_list \
                        if len(list(qu_type.question_set.all())) != 0]
    #print(qu_type_list2)
    #求出问题类型对象的所有关联问题的列表如果不为0时的列表
    for qu_type in qu_type_list2:
        qu_list = list(qu_type.question_set.all())
        type_list.append(len(qu_list))
        
        type_dict[qu_type] = len(qu_list)    #形成 问题类型对象为键 问题个数为值的字典
        
    #print(type_dict)
    
    paper_obj_list = PersonID.objects.get(person_name = teacher_name).savepaper_set.all()
    #print(paper_obj_list)
    paper_dict = {}
    
    for paper_obj in paper_obj_list:
        #paper_dict[paper_obj.paper_name] = paper_obj.paper_info
        paper_dict[paper_obj.paper_name] = Cpaper(paper_obj.paper_info).c_paper()
        
    print(paper_dict)
    #print(paper_list)
    try:
        the_paper = DefaultPaper.objects.get(pk = 1).save_paper.paper_name
    except:
        the_paper = '没有设置默认试卷'
    name_id = PersonID.objects.get(person_name = teacher_name).id
    '''
    if request.session['zhuce']:
        context = {'type_dict':type_dict,'paper_dict':paper_dict,\
                'the_paper':the_paper,'teacher_name':teacher_name,'id':name_id}
        return render(request,'paper/teacher_index.html',context)
    '''
    context = {'type_dict':type_dict,'paper_dict':paper_dict,\
                    'the_paper':the_paper,'teacher_name':teacher_name,'id':name_id,'zhuce':'注册'}

    return render(request,'paper/teacher_index.html',context)
    '''
    try:
        error = request.session['error']
        print(error)
    except:
        return render(request,'paper/teacher_index.html',context)
    else:
        context['error'] = error
        return render(request,'paper/teacher_index.html',context)
    '''
    
    
def index_yunsuan(request):#生成试卷必要运算，用了produce模块的CreatePaper类的方法
    info = dict(request.POST)
    print(info)
    
    create_paper_info = CreatePaper(info)
    context_dict = create_paper_info.info_dict
    print(context_dict)
    context_dict_pk = create_paper_info.info_dict_pk()
                                            #这儿是保存题目到数据库
    teacher_name = request.session['teacher_name']
    
    PersonID.objects.get(person_name = teacher_name).savepaper_set.create\
                                     (paper_name = info['paper_name'][0]+' 生成时间：{}'\
                                      .format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())),\
                                      paper_info = context_dict_pk)
    if request.session['权限'] == '老师':
        username = request.session['teacher_name']
        context_dict['message'] = '老师登录'
        context_dict['teacher_name'] = teacher_name
    elif request.session['权限'] == '学生':
        return HttpResponseRedirect(reverse('login:login',))
    
    #context = {'context_dict':context_dict}   index_yunsuan1.html
    return render(request,'paper/paper_show.html',context_dict)
    


def batch(request):          #老师批卷视图主页
    sf_obj_list = PersonSf.objects.get(person_sf = '学生').personid_set.annotate(Count('savepaper'))
    #每个学生如果保存的试卷不为0的话即可存入列表
    sf_obj_list = [sf_obj for sf_obj in sf_obj_list if sf_obj.savepaper__count != 0]
    
    #print('sf_obj_list',sf_obj_list)
    sf_dict = {}
    paper_list = []
    for sf_obj in sf_obj_list:
        for paper_obj in sf_obj.savepaper_set.all():
            paper_list.append(paper_obj)
        sf_dict[sf_obj] = paper_list
        paper_list = []
    #以上循环写成了一个键是名字，值是该名字所对应的试卷对象的一个列表
    #print('sf_dict',sf_dict)
    sf_info_dict = {}
    for person_obj,paper_list in sf_dict.copy().items():
        sf_info_dict[person_obj] = {}
        for paper_name in paper_list:
            sf_info_dict[person_obj][paper_name] = paper_name.paper_info
    #以上循环写成了一个键是名字，值是一个该名字对应的试卷名字为键，试卷信息为值的字典     
    #print('sf_info_dict',sf_info_dict)
    message_dict = {}
    test_list = []
    score = 0                       #写一段逻辑将试卷详细信息渲染出来
    last_dict = {}
    '''
    for key,value in sf_info_dict.copy().items():
        for paper_obj,paper_info in value.copy().items():
            #print(paper_info)
            info_dict = eval(paper_info)
            message_dict = PatchPaper(info_dict).ConvertInfo()
            
            value[paper_obj] = message_dict
        last_dict[key] = value
        #message_dict = {}
    #print('sf_info_dict',sf_info_dict)
    '''
    
    for key,value in sf_info_dict.items():
        for paper_obj,paper_info in value.items():
            paper_info = eval(paper_info)
            try: 
                #paper_id = paper_obj.id
                the_batch_obj = Batch.objects.get(paper_name = paper_obj)
                
            except Batch.DoesNotExist:
                paper_info['nothing'] = '该试卷还未批阅！'
            else:
                
                paper_info['total_score'] = the_batch_obj.batch_score
                paper_info['message'] = '该试卷已经被打分！'
                #print('这是信息',paper_info)
            value[paper_obj] = paper_info
    #print('最新的：',sf_info_dict)
    
    context = {'sf_dict':sf_dict,'sf_info_dict':sf_info_dict}
    return render(request,'paper/batch.html',context)
    '''
            for question_id,choice_list in info_dict.items():
                question_obj = Question.objects.get(pk = question_id)
                try:
                    
                    choice_obj = Choice.objects.get(pk = choice_list[1])
                    detail_dict[question_obj] = choice_obj
                
                except:
                    detail_dict[question_obj] = choice_list[1]
                else:
                    if choice_obj.choice_text == question_obj.answer_set.all()[0].answer_text:
                        score = score + int(choice_list[0])
                        choice_list.append(int(choice_list[0]))
                    else:
                        choice_list.append(question_obj.answer_set.all()[0].answer_text)
    '''
def batch_detail(request,pk):
    the_paper_obj = SavePaper.objects.get(pk = pk)
    paper_info = eval(the_paper_obj.paper_info)
    #print(paper_info)
    detail_dict = {}
    for key,value in paper_info.items():
        if key == '单选题':            
            value[2] = [(Question.objects.get(pk =question_id),
                         Choice.objects.get(pk = user_answer))
                        for question_id,user_answer in value[2][:]
                        ]
        else:
            value[2] = [(Question.objects.get(pk = question_id),
                         user_answer)
                        for question_id,user_answer in value[2][:]
                        ]
    #print(paper_info)
    teacher_name = request.session['teacher_name']
    request.session['teacher_name'] = teacher_name
    request.session['pk'] = pk
    paper_info['teacher_name'] = teacher_name
    
    
    context = paper_info
    return render(request,'paper/batch_detail.html',context)
def save_batch(request):
    if request.method == 'POST':
        pk = request.session['pk']
        teacher_name = request.session['teacher_name']
        info_dict = dict(request.POST)
        del info_dict['csrfmiddlewaretoken']
        total_score = 0
        for key,value in info_dict.items():
            if key != 'total_score':
                total_score += int(value[0])
        paper_obj = SavePaper.objects.get(pk = pk)
        person_obj = PersonID.objects.get(person_name = teacher_name)
        Batch.objects.create(paper_name = paper_obj,\
                             batch_name = person_obj,batch_detail = info_dict,\
                             batch_score = total_score)
        print(total_score)
        print('信息',info_dict)
        context = {'message':'添加成功！'}
        return render(request,'paper/batch_suc.html',context)
        #return HttpResponse('添加成功！')
    elif request.method == 'GET':
        context = {}
        return HttpResponseRedirect(reverse('login:login'))

def batch_show(request,paper_id):
    the_paper_obj = SavePaper.objects.get(pk = paper_id)
    the_paper_info = eval(the_paper_obj.paper_info)
    
    the_paper_dict = PatchPaper(the_paper_info).ConvertInfo()
    #print(the_paper_dict)
    the_batch_obj = Batch.objects.get(paper_name = the_paper_obj)
    the_batch_info = eval(the_batch_obj.batch_detail)
    
    new_info_dict = {}
    '''
    for key,value in the_batch_info.copy().items():
        if key != 'total_score':
            new_info_dict[int(key)] = value[:]
    #print(new_info_dict)
    '''
        
    #for question in the_paper_dict['单选题'][2]:
        #print(new_info_dict[question[0].id][0])
    for key,value in the_batch_info.items():
        if key != 'total_score':
            qu_obj = Question.objects.get(pk = key)
            new_info_dict[qu_obj] = value[:]
    print(new_info_dict)

    for key,value in the_paper_dict.copy().items():
        if key != 'total_score':
            for que_list in value[2][:]:
                que_list.append(new_info_dict[que_list[0]][0])
        
    print(the_paper_dict)
    the_paper_dict['total_score'] = the_batch_info['total_score'][0]
    
    teacher_name = request.session['teacher_name']
    context = {'the_paper_dict':the_paper_dict,\
               'the_batch_info':new_info_dict,'teacher_name':teacher_name}
    return render(request,'paper/batch_show.html',context)
def random_default(request):    #生成默认试卷
    
    info_dict_default = {
        'question_type1':['1','5','1'],
        'question_type2':['3','5','2'],
        'question_type3':['6','5','2'],
        'question_type4':['5','5','3'],
        }
    produce_paper = ProducePaper(info_dict_default)
    context_dict = produce_paper.info_dict
    context_dict_pk = produce_paper.info_dict_pk() 
    
    context = {'context_dict':context_dict,'context_dict_pk':context_dict_pk}
    return render(request,'paper/random_default_paper.html',context)

def paper_remove(request):
    the_paper = request.POST['删除试卷']
    print(the_paper)
    paper_obj = SavePaper.objects.get(paper_name = the_paper)
    
    try:
        default_obj = DefaultPaper.objects.get(pk = 1)
        print(default_obj)
        if paper_obj.paper_name == default_obj.default_paper:
            request.session['error'] = '您正在删除默认试卷，请重设一张默认试卷后再删除此试卷！'
            #context = {'error':'您正在删除默认试卷，请重设一张默认试卷后再删除此试卷！'}
            return HttpResponseRedirect(reverse('paper:teacher_index'))
        else:        
            paper_obj.delete()
            return HttpResponseRedirect(reverse('paper:teacher_index'))
    except:
        return HttpResponseRedirect(reverse('paper:teacher_index'))

def paper_show(request):    #数据渲染  老师设置某一张试卷为默认试卷并渲染到模板预览
    
    the_info = request.POST['默认试卷']
    paper_obj = SavePaper.objects.get(paper_name = the_info)
    try:
        default_obj = DefaultPaper.objects.get(pk = 1)
        default_obj.save_paper = paper_obj
        default_obj.default_paper = paper_obj.paper_name
        default_obj.save()
    except:
        DefaultPaper.objects.create(save_paper = paper_obj,default_paper = paper_obj.paper_name)  
    finally:
        paper_info = paper_obj.paper_info
        paper_dict = Cpaper(paper_info).c_paper()
    
    teacher_name = request.session['teacher_name']
    quanxian = request.session['权限']
    if quanxian == '老师':
        paper_dict['message'] = '老师登录'
        paper_dict['teacher_name'] = teacher_name
    return render(request,'paper/paper_show.html',paper_dict)

def dati(request):    #数据渲染  学生答题页面
    try:
        permission = request.session['权限']
        student_name = request.session['student_name']
    except KeyError:
        context = {}
        return render(request,'login/denglu.html',context)
    else:  
        paper_info = DefaultPaper.objects.get(pk = 1).save_paper.paper_info
        #print(paper_info)
        paper_dict = Cpaper(paper_info).c_paper()
        print('paper_dict2',paper_dict)
    
        #info = {'单选题':[6,1],'填空题':[5,2],'判断题':[5,1],'英汉互译题':[5,3],'简答题':[2,5]}
        #context =ProducePaper(info).paper_info_obj
        #print(context)

        paper_dict['news'] = '学生登录'
        paper_dict['student_name'] = student_name
        paper_dict.update(request.session)  #利用字典的update方法将session的内容更新到paper_dict里
    
        return render(request,'paper/paper_test.html',paper_dict)

def dati_tijiao_info(request):       #接收考试完提交的信息，并运算
    if request.method == 'GET':
        context = {'message':'请先登录！'}
        return render(request,'login/denglu.html',context)
    elif request.method == 'POST':
        
        info = dict(request.POST)
        del info['csrfmiddlewaretoken']
        print(info)
        '''
        for key,value in info.copy().items():
                if  not key.startswith('csrf') and not key.startswith('paper'):
                    info[key] = value
        '''
        test_obj = DefaultPaper.objects.get(pk = 1).save_paper
        test_info = eval(test_obj.paper_info)
        detail_dict = {}
        for value in test_info.values():
            value[2] = [(i,info[str(i)][1]) for i in value[2]]
            '''
            for i in value[2]:
                detail_dict[i] = info[str(i)][1]     #上面是元组的形式，这是一个字典的形式
                value[2] = detail_dict
            detail_dict = {}
            '''
        student_name = request.session['student_name']
        PersonID.objects.get(person_name = student_name).savepaper_set.create\
                                         (paper_name = student_name + '考试试卷'+\
                                          ' 考试时间：{}'.format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())),\
                                          paper_info = test_info)
        print(test_info)
        context = {'suc':'提交成功，等待老师批卷！','student_name':student_name}
    
        return render(request,'paper/suc.html',context)

def info_jiekou(request):

    context = {}
    return render(request,'paper/info_jiekou.html',context)
    #return HttpResponse('提交成功')
	
def info_jiekou_yunsuan(request):

    '''<QueryDict: {'csrfmiddlewaretoken': 
    ['Xu9GD5AqMDSwOub0pw7Ncjf3DfPB5yjcbcw2Dg
    o9MKAKc196rhH7lZfnWFTQ7R4z'], 
    'question_type': ['1'], 
    'question': ['所有M是P，所有S是M，
    因此不对的结论是（  ）'], 
    'choice': ['所有S是P', '所有S是Px', 
    '所有M是S', ''], 'answer': ['所有M是S']}>
    '''

    info_dict = dict(request.POST)
    type_id = info_dict['question_type'][0]
    if info_dict['question'][0] =='' or info_dict['answer'][0] == '':
        return HttpResponse('请检查是否输入问题和答案')
		
    question_type = QuestionType.objects.get(pk = type_id)
	
    question = question_type.question_set.create(question_text = info_dict['question'][0])
	
    question.answer_set.create(answer_text = info_dict['answer'][0])
	
    for choice in info_dict['choice']:
        if choice != '':
            question.choice_set.create(choice_text = choice)
	
    return HttpResponse('添加成功')
	


